import Vue from 'vue'
import VueRouter from 'vue-router'

//如果所有组件都在这里导入,会导入大量的组件,而且页面打开后,这些代码都将会执行
//实际上导入这么多组件,不一定有用
import MyLogin from '@/components/MyLogin'

Vue.use(VueRouter)

const routes = [
  //一级路由(登录和首页)
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: MyLogin
  },
  //下面的()=>import('@/xxxxx')就是动态导入,当访问这个规则的时候,才会导入,否则就不导入
  {
    path: '/home',
    component: () => import('@/components/MyHome.vue'),
    children: [
      //首页的二级路由(path里面,不要加/,最终的地址会自动拼接成/home/users)
      {
        path: 'goods',
        component: () => import('@/components/menus/MyGoods.vue')
      },
      {
        path: 'orders',
        component: () => import('@/components/menus/MyOrders.vue')
      },
      {
        path: 'rights',
        component: () => import('@/components/menus/MyRights.vue')
      },
      {
        path: 'settings',
        component: () => import('@/components/menus/MySettings.vue')
      },
      {
        path: 'users',
        component: () => import('@/components/menus/MyUsers.vue')
      },
      //用户详情,也展示到了首页的内容区,所以也是首页的二级路由
      {
        path: 'detail/:id',
        component: () => import('@/components/user/MyUserDetail.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//全局前置导航守卫
router.beforeEach((to, from, next) => {
  //to到哪里去 to.path 表示即将要访问的那个地址
  //from从哪里来
  //next()--表示放行,允许通过;next(false)--表示不允许通过;next('/login')--强行跳转到login
  if (to.path === '/login') {
    next() //访问登录页,允许,直接放行
  } else {
    //访问的不是登录页,需要判断有没有token(有token说明登陆过,没有说明退出了或没有登录)
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
